const { MongoClient } = require('mongodb');

class DAO {
    constructor(url, dbName, collectionName) {
        this.url = url;
        this.dbName = dbName;
        this.collectionName = collectionName;
    }
    async connectToMongo() {
        try {
            // 这里直接使用await等待MongoClient.connect返回的Promise
            const client = await MongoClient.connect(this.url);
            return client;
        } catch (err) {
            // 捕获连接过程中的错误并抛出
            throw err;
        }
    }
    insert(obj, isMany) {
        return new Promise((resolve, reject) => {
            const client = this.connectToMongo()
            client.then(client => {
                let db = client.db(this.dbName)
                if (isMany) {
                    db.collection(this.collectionName).insertMany(obj).then(res =>{
                        resolve(res)
                        client.close()
                    })  // 新增多条
                } else {
                    db.collection(this.collectionName).insertOne(obj).then(res =>{
                        resolve(res)
                        client.close()
                    })   // 一条
                }
            })
        })
    }

    del(obj, isMany) {
        return new Promise((resolve, reject) => {
            const client = this.connectToMongo()
            client.then(client => {
                let db = client.db(this.dbName)
                if (isMany) {
                    db.collection(this.collectionName).deleteMany(obj).then(res => {
                        resolve(res)
                        client.close()
                    })  //删除多条
                } else {
                    db.collection(this.collectionName).deleteOne(obj).then(res => {
                        resolve(res)
                        client.close()
                    })
                }
            })
        })
    }

    update(filter, updater) {
        return new Promise((resolve, reject) => {
            const client = this.connectToMongo()
            client.then(client => {
                let updaterCopy = { $set: updater }; 
                let db = client.db(this.dbName); 
                db.collection(this.collectionName).updateMany(filter, updaterCopy).then(res => {
                    resolve(res);
                    client.close()
                })
            })
        })
    }

    query(obj) {        
        obj = obj || {} //查询条件,不传就默认全部
        return new Promise((resolve, reject) => {
            const client = this.connectToMongo()
            client.then(async client => {
               let db = client.db(this.dbName);
               const collection =  db.collection(this.collectionName)
               const queryRes = await collection.find(obj);
               const results = [];
               await queryRes.forEach(doc => results.push(doc));
               resolve(results);
           })

        })
    }
}

module.exports = DAO


// 这个端口是本地运行数据库时反馈的信息 命令是mongosh
// const dao = new DAO('mongodb://localhost:27017/', 'test', 'user')    // 三个参数对于 端口名称，数据库名，表名

// 模拟操作，查询，新增，删除，更新
// let obj = { name: 'kushilin', age: '20' }
// dao.insert(obj).then(res => { console.log(res) })

// let arr = [];
// for (let i = 0; i < 10; i++) {
//     arr.push({
//         userid: '妖怪',
//         age: i
//     })
// }
// dao.insert(arr, true).then(res => { console.log(res) })
// let obj = { userid: '妖怪' }
// dao.del(obj, true).then(res => { console.log(res) })

// let filter = { name: 'fahai' }
// let update = { name: 'xuxian', age: '20' }
// dao.update(filter, update).then(res => {})..